<?php
/**
 * Created by PhpStorm.
 * User: River
 * Email: river0428@gmail.com
 * Date: 2018/11/12
 * Time: 下午3:31
 */

namespace Modules\Admin\Main\Controllers;

use App\Http\Controllers\Controller;
use App\Models\OilCard;
use App\Models\RechargeOrder;
use App\Models\RechargeOrderDetail;
use App\Models\RechargeTask;
use App\Models\User;
use App\OilRecharge;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Modules\Admin\Auth\Facades\AdminAuth;

class RechargeOrderController extends Controller
{
    public function index()
    {
        return view('main::recharge_order', \Request::all());
    }

    public function direct()
    {
        return view('main::recharge_direct_order', \Request::all());
    }

    public function channelsKV(Request $request)
    {
        $data = $query = User::query()->where('is_channel',1)->get();
        return success($data);
    }

    public function all(Request $request)
    {
        $limit    = $request->input('limit', 10);
        $offset   = $request->input('offset', 0);
        $type     = $request->input('type', 1);
        $field_type = $request->input('field_type');
        $keyword  = $request->input('keyword');
        $datetime = $request->input('datetime');
        $status   = $request->input('status');
        $recharge_mode = $request->input('recharge_mode');

        $channel  = $request->input('channel','all');//渠道
        $recharge = $request->input('recharge','all');//套餐
        $market   = $request->input('market','all');
        $platform = $request->input('platform','all');
        $card_type= $request->input('card_type','all');

        $query = RechargeOrder::query();

        $userQuery = (new User())->query();

        if($platform !== 'all'){
            $userQuery = $userQuery->where('app_platform',$platform);
        }

        if($market !== 'all'){
            $userQuery = $userQuery->where('app_channel',$market);
        }

        $user_ids = [];

        if($channel !== 'all'){
            $parent_id = (new User())->query()->where('open_code',$channel)->value('id');
            $userQuery = $userQuery->where('parent_id',$parent_id);

        }

        $user_ids = $userQuery->pluck('id');



        if($user_ids){
            $query = $query->whereIn('user_id',$user_ids->toArray());
        }else{
            $query = $query->where('user_id',-1);
        }

        if($recharge !== 'all'){
            $query = $query->where('months',$recharge);
        }

        if($field_type && !empty($keyword)){
            if($field_type == 'user_id'){
                $query = $query->where('user_id',$keyword);
            }
            if($field_type == 'card_no'){
                $query = $query->where('card_no',$keyword);
            }
            if($field_type == 'card_mobile'){
                $query = $query->where('card_mobile',$keyword);
            }

        }

        if($datetime){
            if(isset($datetime[0])){
                $start_time = strtotime($datetime[0]);
                $datetime[0] = date('Y-m-d 00:00:00',$start_time);
                $query = $query->where('created_at','>=',$datetime[0]);
            }
            if(isset($datetime[1])){
                $end_time = strtotime($datetime[1]);
                $datetime[1] = date('Y-m-d 23:59:59',$end_time);
                $query = $query->where('created_at','<=',$datetime[1]);
            }

        }

        //if ($datetime && isset($datetime[0]) && isset($datetime[1])) {
        //    $query->whereBetween('created_at', $datetime);
        //}

        if($card_type !== 'all'){
            $query = $query->where('card_type', $card_type);
        }

        if($type !== 'all'){
            $query = $query->where('type', $type);
        }

        if($status==='all') {
            $query = $query->where('status', '>', 0);
        }else{
            if($status==1){
                $query = $query->where('status', '>=', intval($status))->where('status','<',7);
            }else {
                $query = $query->where('status', '=', intval($status));
            }
        }

        if($recharge_mode==='all') {

        }else{
            $query = $query->where('recharge_mode', '=', intval($recharge_mode));
        }

        $data['total'] = $query->count();
        $data['total_recharge_amount'] = $query->sum(DB::raw('recharge_amount * months'));
        $data['total_pay_amount'] = $query->sum('pay_amount');
        $res = $query->take($limit)->skip($offset)->orderBy('id', 'desc')
            ->with(['user', 'oilCard','pay','coupon'])
            ->get();

        $data['items'] = [];
        foreach ($res as $item) {
            $_item = $item->toArray();
//            isset($_item['user']['mobile']) && $_item['user']['mobile'] = AdminAuth::user()->is_super ? $_item['user']['mobile'] : ($_item['user']['mobile']);
//            isset($_item['oil_card']['mobile']) && $_item['oil_card']['mobile'] = AdminAuth::user()->is_super ? $_item['oil_card']['mobile'] : ($_item['oil_card']['mobile']);
//            if (isset($_item['user']['mobile'])) {
//                $_item['user']['mobile'] = convert_mobile($_item['user']['mobile']);
//            }
            if (isset($_item['oil_card']['mobile'])) {
                $_item['oil_card']['mobile_en'] = encrypt($_item['oil_card']['mobile']);
//                $_item['oil_card']['mobile'] = convert_mobile($_item['oil_card']['mobile']);
            }
//            if (!empty($_item['user_mobile'])) {
//                $_item['user_mobile'] = convert_mobile($_item['user_mobile']);
//            }
            $data['items'][] = $_item;
        }

        return success($data);
    }

    public function doRefund(Request $request)
    {
        $order_id = $request->input('order_id');
        $order = RechargeOrder::query()->find($order_id);
        if($order && ($order->status==1 || $order->status==2 || $order->status==3)){
            DB::beginTransaction();
            try{
                $next = RechargeOrder::query()->where('id',$order_id)->update(['status'=>7]);
                if($next) {
                    RechargeOrderDetail::query()->where('recharge_order_id', $order_id)->where('result_status', '<>', 1)->update(['result_status' => 7]);
                    RechargeTask::query()->where('recharge_order_id', $order_id)->where('status', '<>', 9)->update(['status' => 7]);
                }
                DB::commit();
            }catch(\Exception $e){
                DB::rollBack();
            }
        }
        return success();
    }

    public function doCancel(Request $request)
    {
        $order_id = $request->input('order_id');
        $order = RechargeOrder::query()->find($order_id);
        if($order && $order->status==0){
            RechargeOrder::query()->where('id',$order_id)->where('status',0)->update(['status'=>-1]);
        }
        return success();
    }

    public function failTask()
    {
        return view('main::recharge_task_fail', \Request::all());
    }

    public function task(Request $request)
    {
        $limit  = $request->input('limit', 10);
        $offset = $request->input('offset', 0);
        $orderId = $request->input('order_id');
        $type = $request->input('type');
        $field = $request->input('field');
        $value = $request->input('keyword');

        $where = function($q) use ($orderId, $type,$field,$value) {
            if ($orderId) {
               $q->where('recharge_order_id', $orderId);
            }

            // 0待充值，1请求充值成功，2请求充值失败，4充值失败，9充值成功
            if ($type == 2) {
               $q->whereIn('status', [2, 4]);
            }

            if($field && $value){
                if($field=='card_no'){
                    $q->where('card_no',$value);
                }
                if($field=='mobile'){
                    $q->where('card_mobile',$value);
                }
            }
        };

        $data['total'] = RechargeTask::where($where)->count();
        $res = RechargeTask::where($where)
            ->take($limit)
            ->skip($offset)
            ->orderBy('pay_at', 'asc')->get();

        $data['items'] = [];
        foreach ($res as $item) {
            $_item = $item->toArray();
//            $_item['card_mobile'] = AdminAuth::user()->is_super ? $_item['card_mobile'] : ($_item['card_mobile']);
            $_item['mobile_en'] = encrypt($_item['card_mobile']);
            $_item['card_mobile'] = convert_mobile($_item['card_mobile']);

            $data['items'][] = $_item;
        }

//        foreach ($data['items'] as &$item) {
//            if ($item['result']) {
//                $item['result'] = json_decode($item['result'], true);
//            }
//        }

        return success($data);
    }

    public function tryRecharge($id)
    {
        $task = RechargeTask::find($id);
        //$result = OilRecharge::query($task);
        $result = true;
        if($task->status === 2 || $task->status === 4){
            $task->status = 0;
            $task->sn = str_random(32);
            $result = $task->save();
        }
        $this->recordAction('对任务<'.$id.'>重新发起了充值请求');
        return success(['result' => $result ? 1 : 0]);
    }

    public function map()
    {
        return view('main::recharge_order_map', \Request::all());
    }

    public function mapdata(Request $request)
    {
        $datetime = $request->input('datetime');
        $data = [];
        $start_time = time()-3600*24*30;
        $end_time = time();

        if($datetime){
            if(isset($datetime[0])){
                $start_time = strtotime($datetime[0]);
            }
            if(isset($datetime[1])){
                $end_time = strtotime($datetime[1]);
            }
        }

        $start_time = date('Y-m-d 00:00:00',$start_time);
        $end_time = date('Y-m-d 23:59:59',$end_time);

        $result = RechargeOrder::query()->where('status','>',0)
            ->whereBetween('created_at',[$start_time,$end_time])
            ->groupBy('datefield')->select(DB::raw('date(created_at) as datefield,sum(pay_amount) as total'))
            ->get();

        $orders1 = RechargeOrder::query()->where('status','>',0)->where('type',1)
            ->whereBetween('created_at',[$start_time,$end_time])
            ->groupBy('datefield')->select(DB::raw('date(created_at) as datefield,sum(pay_amount) as total'))
            ->pluck('total','datefield');

        $orders2 = RechargeOrder::query()->where('status','>',0)->where('type',2)
            ->whereBetween('created_at',[$start_time,$end_time])
            ->groupBy('datefield')->select(DB::raw('date(created_at) as datefield,sum(pay_amount) as total'))
            ->pluck('total','datefield');

        $datefields = [];
        $orderdata = [];
        $orderdata1 = [];
        $orderdata2 = [];
        foreach($result as $row){
            $datefields[] = $row['datefield'];
            $orderdata[] = $row['total'];
            $orderdata1[] = isset($orders1[$row['datefield']]) ? $orders1[$row['datefield']] : 0;
            $orderdata2[] = isset($orders2[$row['datefield']]) ? $orders2[$row['datefield']] : 0;
        }



        $items = [
            ['name'=>'总充值金额','type'=>'line','stack'=>'','data'=>$orderdata],
            ['name'=>'油卡套餐金额','type'=>'line','stack'=>'','data'=>$orderdata1],
            ['name'=>'油卡直充金额','type'=>'line','stack'=>'','data'=>$orderdata2],
        ];

        $data['items'] = $items;
        $data['datefields'] = $datefields;
        return success($data);
    }

    public function handleRecharge(Request $request)
    {
        $order_id = $request->input('id');
        $handle_remark = $request->input('handle_remark');
        $order = RechargeOrder::query()->find($order_id);
        if(!$order){
            return fail(400,'订单不存在');
        }
        DB::beginTransaction();
        try {
            //更新订单表
            $next = (new RechargeOrder())->query()->where('id', $order_id)
                ->where('recharge_mode',1)
                ->update(['handle_remark' => $handle_remark, 'recharge_mode' => 2]);
            //更新订单详情表
            $next = (new RechargeOrderDetail())->query()
                ->where('recharge_order_id',$order_id)
                ->where('recharge_mode',1)
                ->where('result_status','<>',1)
                ->update(['recharge_mode'=>2]);
            //更新任务表
            $next = (new RechargeTask())->query()
                ->where('recharge_order_id',$order_id)
                ->where('recharge_mode',1)
                ->where(function($query){
                    $query = $query->where('status',0)->orWhere('status',2)->orWhere('status',4);
                })
                ->update(['recharge_mode'=>2]);

            DB::commit();
            $this->recordAction('更改了订单充值方式<' . $order_id . '>为手动充值',$order->toArray());
            return success();
        }catch(\Exception $e){
            Log::error($e->getMessage());
            DB::rollBack();
        }
        return fail(400,'数据更新错误');
    }

    //今日待充值任务
    public function schoduleTask(){
        return view('main::recharge_task_schedule', \Request::all());
    }

    public function scheduleTaskOrder(Request $request)
    {
        $limit = $request->input('limit', 10);
        $offset = $request->input('offset', 0);
        $orderId = $request->input('order_id');
        $type = $request->input('type');
        $field = $request->input('field');
        $value = $request->input('keyword');

        $where = function ($q) use ($orderId, $type, $field, $value) {
            if ($orderId) {
                $q->where('recharge_order_id', $orderId);
            }
            $orderTime = strtotime(date('Y-m-d') . ' 00:00:00');
            $q->whereDate('pay_at', '<=', date('Y-m-d', $orderTime + 60 * 60 * 24));
            // 0待充值，1请求充值成功，2请求充值失败，4充值失败，9充值成功
            if ($type == 2) {
                $q->where('status', 0);
            }
            $q->where('recharge_mode', 2);
            if ($field && $value) {
                if ($field == 'card_no') {
                    $q->where('card_no', $value);
                }
                if ($field == 'mobile') {
                    $q->where('card_mobile', $value);
                }
            }
        };

        //查询近期待充值的手动订单
        $orderData = RechargeTask::where($where)->orderBy('id', 'asc')->get();
        if ($orderData->count()) {
            $orderArray = [];
            foreach ($orderData as $item) {
                $orderArray[] = $item['recharge_order_id'];
            }
            //去重
            $orderArray = array_unique($orderArray);
            $cellData = [];
            //遍历数组
            foreach ($orderArray as $k => $v) {
                //查询待充值任务
                $taskOrder = RechargeTask::where("recharge_order_id", $v)->where("status", 0)->with('order')->orderBy('id', 'asc')->first();
                //查询油卡
                $cardData = OilCard::where('card_no', $taskOrder['card_no'])->where('is_company_card', 1)->where('status', 1)->first();
                if ($cardData) {
                    $rechargeOrder = RechargeOrder::where("oil_card_id", $cardData['id'])->where("status", '>', 0)->orderBy('id', 'asc')->first();
                    if ($rechargeOrder) {
                        if ($rechargeOrder['id'] == $v) {
                            $remark = "--";
                        } else {
                            $remark = "复充";
                        }
                    } else {
                        $remark = "--";
                    }
                    $company = "公司副卡";
                } else {
                    $company = "个人油卡";
                    $remark = "--";
                }

                if ($taskOrder['card_type'] == 1) {
                    $card_type = "中石化";
                } else {
                    $card_type = "中石油";
                }
                if ($taskOrder['status'] == 9) {
                    $statusName = "充值成功";
                } elseif ($taskOrder['status'] == 0) {
                    $statusName = "待充值";
                } elseif ($taskOrder['status'] == 7) {
                    $statusName = "已退款";
                } else {
                    $statusName = "充值失败";
                }
                if ($taskOrder['order']['type']==1){
                    $rechargeType = "套餐";
                }else{
                    $rechargeType = "直充";
                }
                $item = [
                    "id" => $v,
                    "order_sn" => $taskOrder['order']['order_sn'],
                    "card_no" => $taskOrder['card_no'],
                    "card_type" => $card_type,
                    "recharge_amount" => $taskOrder['order']['recharge_amount'],
                    "months" => $taskOrder['order']['months'],
                    "pay_amount" => $taskOrder['order']['pay_amount'],
                    "card_name" => $taskOrder['card_name'],
//                    "card_mobile" => $taskOrder['card_mobile'],
                    "card_mobile" => convert_mobile($taskOrder['card_mobile']),
                    "mobile_en" => encrypt($taskOrder['card_mobile']),
                    "recharge_type"=>$rechargeType,
                    "recharge_mode" => "手动",
                    "is_company" => $company,
                    "remark" => $remark,
                    "status_name" => $statusName,
                    "pay_at" => date('Y-m-d',strtotime($taskOrder['pay_at']))
                ];
                $cellData[] = $item;
            }
            $start = ($offset-1)*$limit;
            $data['total'] = count($cellData);
            $data['items'] = array_slice($cellData,$start,$limit);
            return success($data);
        }
    }

    public function handRecharge(Request $request){
        try {
            $id = $request->input("id");
            $rechargeDate = $request->input("pay_at");
            $task = RechargeOrder::find($id);
            if ($task){
                //查询当前日期的充值订单
                $taskOrder = RechargeTask::where("recharge_order_id",$id)->whereDate("pay_at",">=",$rechargeDate.' 00:00:00')->whereDate("pay_at","<=",$rechargeDate."23:59:59")->get();
                $result = true;
                foreach ($taskOrder as $k=>$v){
                    if ($v->status === 0) {
                        $v->status = 9;
                        $v->sn = str_random(32);
                        $result = $v->save();
                    }
                }
                $this->recordAction('对任务<' . $id . '>重新发起了充值请求');
                return success(['result' => $result ? 1 : 0]);
            }

            //$result = OilRecharge::query($task);
        }catch (\Exception $e){
            Log::error($e);
            return fail(500,"系统错误");
        }
    }

    /**
     * 更换充值油卡
     *
     * @author yls
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function changeCard(Request $request)
    {
        $orderId = $request->get('order_id', 0);
        $userId  = $request->get('user_id', 0);
        $cardId = $request->get('card_id', 0);

        if (empty($orderId) || empty($userId) || empty($cardId)) {
            return fail(400,"参数错误");
        }

        DB::beginTransaction();
        try {
            $orderInfo = RechargeOrder::query()->where([
                ['id', '=', $orderId],
                ['user_id', '=', $userId],
            ])->first();

            $cardInfo = OilCard::query()->where([
                ['id', '=', $cardId],
                ['user_id', '=', $userId],
                ['status', '=', 1]
            ])->first();
            if (empty($cardInfo)) {
                return fail(400,"油卡不存在");
            }

            // 更改订单
            RechargeOrder::query()->where([
                ['id', '=', $orderId],
                ['user_id', '=', $userId],
            ])->update(['card_no' => $cardInfo->card_no, 'card_type' => $cardInfo->type, 'oil_card_id' => $cardInfo->id]);

            // 更改订单详情
            RechargeOrderDetail::query()->where([
                ['recharge_order_id', '=', $orderId],
                ['user_id', '=', $userId],
                ['is_paid', '=', 0]
            ])->update(['card_type' => $cardInfo->type, 'card_no' => $cardInfo->card_no, 'card_mobile' => $cardInfo->mobile, 'oil_card_id' => $cardInfo->id]);

            // 更改充值脚本
            RechargeTask::query()->where([
                ['recharge_order_id', '=', $orderId],
                ['status', '=', 0],
            ])->update(['card_type' => $cardInfo->type, 'card_mobile' => $cardInfo->mobile, 'card_no' => $cardInfo->card_no, 'card_name' => $cardInfo->name]);

            $this->recordAction('订单' . $orderInfo->order_sn . '的充值油卡由'.$orderInfo->card_no.'更改为'.$cardInfo->card_no, ['order'=>$orderInfo]);

            DB::commit();
            return success(['result' => 1]);
        } catch (\Exception $e) {
            DB::rollBack();
            return fail(500,"系统错误".$e->getMessage());
        }
    }

    /**
     * 拨打电话
     *
     * @author yls
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function call(Request $request)
    {
        $cardId = $request->get('card_id', 0);
        if (empty($cardId)) {
            return fail(400, '找不到数据');
        }

        $order = OilCard::query()->where('id', $cardId)->first();
        if (empty($order)) {
            return fail(400, '找不到数据');
        }

        if (empty($order->mobile)) {
            return fail(400, '手机号码不存在');
        }

        $res = $this->hollycrmCall($order->mobile);

        return $res ? success($res) : fail(400, '拨号失败');
    }
}